package com.yxkj.syh.app.huarong.activities.orders.detail.status_other;

import android.app.Application;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.syh.app.basic.base.BaseResponse;
import com.syh.app.basic.base.view_model.BaseViewModel;
import com.syh.app.basic.utils.DateUtils;
import com.syh.app.basic.utils.Tooast;
import com.syh.app.basic.utils.net.ApiObserver;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.yxkj.syh.app.huarong.bean.CheckInfo;
import com.yxkj.syh.app.huarong.bean.OrderDetail;
import com.yxkj.syh.app.huarong.bean.OrderDetailResponse;
import com.yxkj.syh.app.huarong.bean.OrderInfo;
import com.yxkj.syh.app.huarong.bean.OrderProcess;
import com.yxkj.syh.app.huarong.bean.UploadImageResponse;
import com.yxkj.syh.app.huarong.constants.OrderStatus;
import com.yxkj.syh.app.huarong.data_center.model.OrderModel;
import com.yxkj.syh.app.huarong.data_center.model.UploadModel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import mlxy.utils.S;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 创建者：SYH
 * 时间：2020/5/20 13:20
 * 编辑者：SYH、
 * 标签：
 * 补充说明：
 */
public class OrderOtherStatusVM extends BaseViewModel<ActivityEvent> {

    public OrderOtherStatusVM(@NonNull Application application) {
        super(application);
    }

    public ObservableField<String> ofStatusText = new ObservableField<>();
    public ObservableField<String> ofLineType = new ObservableField<>();
    public ObservableField<String> ofFromAddress = new ObservableField<>();
    public ObservableField<String> ofToAddress = new ObservableField<>();
    public ObservableField<String> ofCarHeadNo = new ObservableField<>();
    public ObservableField<String> ofCarTrailerNo = new ObservableField<>();
    public ObservableField<String> ofRemrk = new ObservableField<>();
    public ObservableField<String> ofOrderNo = new ObservableField<>();
    public ObservableField<String> ofCreatTime = new ObservableField<>();
    public ObservableField<String> ofFacheTime = new ObservableField<>();
    public ObservableField<String> ofFinishTime = new ObservableField<>();
    public ObservableField<Boolean> ofHasShdfUrl = new ObservableField<>(Boolean.FALSE);
    public ObservableField<Boolean> ofHasShdsUrl = new ObservableField<>(Boolean.FALSE);
    public ObservableField<String> ofButtonText = new ObservableField<>();

    public MutableLiveData<OrderInfo> mldOrderDetail = new MutableLiveData<>();
    public MutableLiveData<Boolean> mldFinishOrder = new MutableLiveData<>();
    public MutableLiveData<Boolean> mldApplyPayOrder = new MutableLiveData<>();
    public MutableLiveData<String> mldImageUrl = new MutableLiveData<>();

    /**
     * 上传图片
     *
     * @param file
     */
    public void uploadImage(File file) {
        showLoading("getUploadModel");
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
        UploadModel.getUploadModel().uploadImage(filePart, mLifecycleProvider.bindToLifecycle(), new ApiObserver<UploadImageResponse>() {
            @Override
            public void onSuccess(UploadImageResponse response) {
                hideLoading("getUploadModel");
                mldImageUrl.setValue(response.getData());
                Tooast.success("上传成功");
            }

            @Override
            public void onFailed(int code, String msg) {
                hideLoading("getUploadModel");
                Tooast.warning(msg);
            }
        });
    }


    /**
     * 签收
     */
    public void orderFinish(List<String> imageUrls) {
        showLoading("orderFinish");
        Map<String, Object> pMap = new HashMap<>();
        pMap.put("orderId", mldOrderDetail.getValue().getId());
        if (imageUrls != null && imageUrls.size() > 0) {//非空车单
            JSONArray credentials = new JSONArray();
            for (String imageUrl : imageUrls)
                credentials.put(imageUrl);
            pMap.put("credentials", credentials.toString());
            pMap.put("isEmpty", 0);
        } else {
            pMap.put("isEmpty", 1);
        }
        OrderModel.getOrderModel().orderFinish(pMap, mLifecycleProvider.bindToLifecycle(), new ApiObserver<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse response) {
                Tooast.success(response.getMessage());
                mldFinishOrder.setValue(true);
                hideLoading("orderFinish");
            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
                mldFinishOrder.setValue(false);
                hideLoading("orderFinish");
            }
        });
    }

    /**
     * 申请支出单
     */
    public void applyPayOrder() {
        showLoading("applyPayOrder");
        Map<String, Object> pMap = new HashMap<>();
        pMap.put("toOrderId", mldOrderDetail.getValue().getId());
        pMap.put("toOrderNo", mldOrderDetail.getValue().getNo());
        OrderModel.getOrderModel().applyPayOrder(pMap, mLifecycleProvider.bindToLifecycle(), new ApiObserver<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse response) {
                Tooast.success(response.getMessage());
                mldApplyPayOrder.setValue(true);
                hideLoading("applyPayOrder");
            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
                mldApplyPayOrder.setValue(false);
                hideLoading("applyPayOrder");
            }
        });
    }

    public void getOrderDetail(long id) {
        OrderModel.getOrderModel().orderDetail(id, mLifecycleProvider.bindToLifecycle(), new ApiObserver<OrderDetailResponse>() {
            @Override
            public void onSuccess(OrderDetailResponse orderDetailResponse) {

                mldOrderDetail.setValue(orderDetailResponse.getData());

            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
            }
        });
    }

    public List<String> getLogCredentials(int action, int flag) {
        String arrayStr = "";
        List<OrderProcess> processes = mldOrderDetail.getValue().getOrderProcessList();

        for (OrderProcess process : processes) {
            if (process.getActionCode() == action) {
                if (process.getFlag() == flag) {
                    arrayStr = process.getCredentials();
                    break;
                }
            }
        }
        List<String> urls = new ArrayList<>();
        if (!TextUtils.isEmpty(arrayStr)) {
            try {
                JSONArray jsonArray = new JSONArray(arrayStr);
                for (int i = 0; i < jsonArray.length(); i++) {
                    urls.add((String) jsonArray.get(i));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return urls;
    }

    /**
     * 获取时间
     */
    public String getOrderTime(int action) {
        List<OrderProcess> processes = mldOrderDetail.getValue().getOrderProcessList();

        for (OrderProcess process : processes) {
            if (process.getActionCode() == action) {
                if (process.getFlag() == 1) {
                    return process.getCreateTime();
                }
            }
        }
        return "--";
    }


}
